#icoach module
#!/usr/bin/python
#Filename: icoach.py

import os
import cgi
import logging
import urllib

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import mail
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms
from google.appengine.ext.webapp.util import run_wsgi_app


class Log(db.Model):
     log_date = db.DateTimeProperty(auto_now_add=True)
     account = db.UserProperty()

def getCurrentProfile():
    '''Returns the Profile of the current user, or None if the user does not have one or is not logged in.'''
    if users.get_current_user():
        query = Profile.all()
        query.filter('account =',users.get_current_user())
        return query.get()
    logging.debug('No Profile found')
    return None

def getProfile(email):
    '''Returns the Profile of the user with email or None if no one has that email.'''
    query = Profile.all()
    query.filter('email =', email)
    return query.get()

class MainPage(webapp.RequestHandler):
    '''Main Page View'''
    def get(self):
        logging.debug('Begin checking if profile exists for current user')      
        if users.get_current_user() == None: #user is not logged into google.
            logging.debug('No user')
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            user = ''
        else: #user logged in, check if he has a profile
            logging.debug('User %s logged in' % users.get_current_user().email())
            userProfile = getCurrentProfile()
            if userProfile == None: #no profile, create one
                userProfile = getProfile(users.get_current_user().email()) #try fetching profile via email, in case the admin created it
                if userProfile != None: #user has profile but profile.account is not set, set it.
                    userProfile.account = users.get_current_user()
                    logging.debug('Setting profile.account to this account')
                else:
                    logging.debug('Creating new Profile')
                    email = users.get_current_user().email()
                    userProfile = Profile(account=users.get_current_user(),email=email)
                userProfile.put()
                self.redirect('/profile/%s?action=edit' % email)
            else:
                logging.debug('User already has profile: email=%s' % userProfile.email)
                
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            user = users.get_current_user().email()
        
        if users.is_current_user_admin():
            template_values = {
            'user': user,
            'url': url,
            'url_linktext': url_linktext,
            'admin': True
            }
        else:    
            template_values = {
            'user': user,
            'url': url,
            'url_linktext': url_linktext
            }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class ProfileHandler(webapp.RequestHandler):
    '''Serves up profile for user'''
    def get(self):
        logging.debug('We are in Profile')
        path = self.request.path
        result = path.split('/', 4)
        urlUser = result[2]     
        logging.debug('urlUser=%s' % urlUser)
        if users.get_current_user():
            useremail = urllib.quote(users.get_current_user().email())
        else:
            useremail = ''
        logging.debug('user=%s' %  useremail)            
        url = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout'
         
        if urlUser == '' and users.is_current_user_admin() : 
            #request for /profile/, show admin all profiles
            logging.debug('admin asking for list of users')
            query = Profile.all()
            userList = [p.email for p in query]
            template_values = {
                               'user' : users.get_current_user(),
                               'url': url,
                               'url_linktext': url_linktext,
                               'userList': userList,
                               'admin': True}
            htmlFile = os.path.join(os.path.dirname(__file__), 'logsList.html')
            self.response.out.write(template.render(htmlFile, template_values))
                                                                                           
        elif users.get_current_user() and ((useremail == urlUser) or  users.is_current_user_admin()): 
            #show user or admin user's profile, ONLY (for now)
            email = urllib.unquote(urlUser)
            userProfile = getProfile(email)
            if userProfile == None: #that user does not exist, create an empty profile, but DO NOT PUT() it in database
                userProfile = Profile()          
            template_values = {
                               'user': urllib.unquote(urlUser),
                               'url': url,
                               'url_linktext': url_linktext,
                               'bday': userProfile.bday,
                               'phone_car' : userProfile.phone_car,
                               'phone_num': userProfile.phone_num,
                               'due_date': userProfile.due_date,
                               'pre_weight': userProfile.pre_weight,
                               'height': userProfile.height,
                               'age': userProfile.age,
                               'bmi': userProfile.bmi,
                               'name': userProfile.name,
                               'tmz': userProfile.tmz,
                               'edit': False,
                               }                
            htmlFile = os.path.join(os.path.dirname(__file__), 'profile.html')
            self.response.out.write(template.render(htmlFile, template_values))
            
        else: #no such user, put up error page.
            logging.debug('No such user')
            template_values = {
                               'user': 'Login',
                               'url': '/',
                               'url_linktext': 'Login'
                               }
            path = os.path.join(os.path.dirname(__file__), 'index.html')
            self.response.out.write(template.render(path, template_values))
   
    def post(self):
        """Update the user's profile with the information in the POST"""
        pass
    
class Admin(webapp.RequestHandler):
    def get(self):    
        if users.is_current_user_admin():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'       
            template_values = {
                               'url': url,
                               'url_linktext': url_linktext,
                               'admin': True
                               }                
            htmlFile = os.path.join(os.path.dirname(__file__), 'admin.html')
            self.response.out.write(template.render(htmlFile, template_values))
        else:
            logging.debug('No such user')
            template_values = {
                               'user': 'Login',
                               'url': '/',
                               'url_linktext': 'Login'
                               }
            path = os.path.join(os.path.dirname(__file__), 'index.html')                    
        
application = webapp.WSGIApplication([('/', MainPage), ('/admin/', Admin)], debug=True)
  
def main():
     logging.getLogger().setLevel(logging.DEBUG)
     run_wsgi_app(application)

if __name__ == "__main__":
     main()
